package com.yequan.designpattern.singleton;

import java.io.*;

/**
 * @Auther: yq
 * @Date: 2019/1/9 16:38
 * @Description:
 */
public class SerializableStaticInnerClassSingleton implements Serializable {

    private static final long seriaVersionUUID=1L;

    /**
     * 静态内部类实现单例模式（线程安全）
     * 在序列化与反序列化中也是单例的，在代码中必须重写 readResolve()方法
     */
    private static class SerializableStaticInnerClassSingleTonHandler{
        private static SerializableStaticInnerClassSingleton instance=new SerializableStaticInnerClassSingleton();
    }

    private SerializableStaticInnerClassSingleton(){}

    public static SerializableStaticInnerClassSingleton getInstance(){
        try {
            Thread.sleep(300);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return SerializableStaticInnerClassSingleTonHandler.instance;
    }

    //该方法在反序列化时会被调用，该方法不是接口定义的方法，有点儿约定俗成的感觉
    protected Object readResolve() throws ObjectStreamException {
        System.out.println("调用了readResolve方法！");
        return SerializableStaticInnerClassSingleTonHandler.instance;
    }

    public static void main(String[] args) {
        SerializableStaticInnerClassSingleton singleton = SerializableStaticInnerClassSingleton.getInstance();

        File file = new File("MySingleton.txt");

        try {
            //序列化对象
            FileOutputStream fos = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fos);
            oos.writeObject(singleton);
            fos.close();
            oos.close();
            System.out.println(singleton.hashCode());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        try {
            FileInputStream fis = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fis);
            SerializableStaticInnerClassSingleton rSingleton = (SerializableStaticInnerClassSingleton) ois.readObject();
            fis.close();
            ois.close();
            System.out.println(rSingleton.hashCode());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }

    }

}
